package com.designPattern.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 24小时代练
 * @author : liutianlong
 * @date : 2023/5/25
 * @since : 1.0
 */
public class WholeDayFactory<T> implements InvocationHandler {

    //被代理的对象
    private Object target = null;

    public WholeDayFactory(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if(this.target == null) {
            System.out.println("被代理对象为空！");
            return null;
        }

        System.out.println("我是代练");
        Object result = method.invoke(this.target, args);
        return result;
    }

    /**
     * 根据被代理对象生成新的代理对象
     * @return
     */
    public <T> T createProxy() {
        if(this.target == null) {
            System.out.println("被代理对象为空！");
            return null;
        }
        ClassLoader classLoader = this.target.getClass().getClassLoader();
        Class<?>[] interfaces = this.target.getClass().getInterfaces();
        Object proxyInstance = Proxy.newProxyInstance(classLoader, interfaces, this);
        return (T)proxyInstance;
    }
}
